Sets


Sets in JavaScript are collections of unique values. Each value can only occur once in a set.

1. Creating a Set

You can create a set using the Set constructor:

const set = new Set([1, 2, 3, 4, 5]);
console.log(set); // Outputs: Set { 1, 2, 3, 4, 5 }

2. Adding and Deleting Elements

You can add and delete elements from a set using the add() and delete() methods:

const set = new Set();
set.add(1);
set.add(2);
set.add(3);
console.log(set); // Outputs: Set { 1, 2, 3 }

set.delete(2);
console.log(set); // Outputs: Set { 1, 3 }

3. Checking for Elements

You can check if a set contains a specific element using the has() method:

const set = new Set([1, 2, 3]);
console.log(set.has(2)); // Outputs: true
console.log(set.has(4)); // Outputs: false

4. Iterating Over a Set

You can iterate over the elements of a set using the for...of loop:

const set = new Set([1, 2, 3]);
for (let value of set) {
    console.log(value);
}
// Outputs: 1 2 3

5. Converting a Set to an Array

You can convert a set to an array using the Array.from() method or the spread operator:

const set = new Set([1, 2, 3]);
const array = Array.from(set);
console.log(array); // Outputs: [1, 2, 3]

const array2 = [...set];
console.log(array2); // Outputs: [1, 2, 3]

6. Set Operations

Sets support various operations like union, intersection, and difference:

const setA = new Set([1, 2, 3]);
const setB = new Set([3, 4, 5]);

// Union
const union = new Set([...setA, ...setB]);
console.log(union); // Outputs: Set { 1, 2, 3, 4, 5 }

// Intersection
const intersection = new Set([...setA].filter(x => setB.has(x)));
console.log(intersection); // Outputs: Set { 3 }

// Difference
const difference = new Set([...setA].filter(x => !setB.has(x)));
console.log(difference); // Outputs: Set { 1, 2 }